<template>
  <el-dialog v-model="visible" :title="!dataForm.id ? '新增' : '编辑'" :close-on-click-modal="false" :close-on-press-escape="false">
    <el-form :model="dataForm" :rules="dataRule" ref="dataFormRef" @keyup.enter.native="dataFormSubmitHandle()" label-width="120px">
      <el-form-item prop="dictValue" label="字典值">
        <el-input v-model="dataForm.dictValue" placeholder="字典值"></el-input>
      </el-form-item>
      <el-form-item prop="dictLabel" label="字典标签">
        <el-input v-model="dataForm.dictLabel" placeholder="字典标签"></el-input>
      </el-form-item>
      <el-form-item prop="sort" label="排序">
        <el-input-number v-model="dataForm.sort" controls-position="right" :min="0" label="排序"></el-input-number>
      </el-form-item>
      <el-form-item prop="remark" label="备注">
        <el-input v-model="dataForm.remark" placeholder="备注"></el-input>
      </el-form-item>
    </el-form>
    <template slot="footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmitHandle()">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import debounce from 'lodash/debounce'
import {computed, nextTick, reactive, ref} from "vue";

import http from "../../../utils/request.js";
import {message} from "../../../utils/commonScript.js";

const emit = defineEmits(['refreshDataList'])

const visible = ref(false)
const dataForm = reactive({
	id: '',
	dictTypeId: '',
	dictLabel: '',
	dictValue: '',
	sort: 0,
	remark: ''
})
const dataFormRef = ref()
const dataRule = computed(() => {
	return {
		dictLabel: [
			{ required: true, message: '必填项不能为空', trigger: 'blur' }
		],
		dictValue: [
			{ required: true, message: '必填项不能为空', trigger: 'blur' }
		],
		sort: [
			{ required: true, message: '必填项不能为空', trigger: 'blur' }
		]
	}
})
const init = (dictTypeId, id='') => {
	visible.value = true
	dataForm.id = id
	dataForm.dictTypeId = dictTypeId
	nextTick(() => {
		dataFormRef.value.resetFields()
		if (dataForm.id) {
			getInfo()
		}
	})
}
// 获取信息
const getInfo = () => {
	http.get(`/sys/dict/data/${dataForm.id}`).then(({ data: res }) => {
		if (res.code !== 0) {
			return message.error(res.msg)
		}
		dataForm.dictTypeId = res.data.dictTypeId
		dataForm.dictValue = res.data.dictValue
		dataForm.sort = res.data.sort
		dataForm.remark = res.data.remark
	}).catch(() => {})
}
// 表单提交
const dataFormSubmitHandle = debounce(function () {
	dataFormRef.value.validate((valid) => {
		if (!valid) {
			return false
		}
		http[!dataForm.id ? 'post' : 'put']('/sys/dict/data', dataForm).then(({ data: res }) => {
			if (res.code !== 0) {
				return message.error(res.msg)
			}
			message({
				message: '操作成功',
				type: 'success',
				duration: 500,
				onClose: () => {
					visible.value = false
					emit('refreshDataList')
				}
			})
		}).catch(() => {})
	})
}, 1000, { 'leading': true, 'trailing': false })

defineExpose({
	init
})
</script>
